#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import util
from LinkedInAPI import LoginHandler
from leader import LeaderboardHandler
import Cookie
from django.utils import simplejson as json
import random
import datastoreWrapper
import os
from google.appengine.ext.webapp import template
#import QDBInterpreter
from question import Question
import logging

catagories = ['first-name', 'last-name', 'patent', 'publication']

class MainHandler(webapp.RequestHandler):
	def get(self):
		self.response.out.write('Hello world!')
		topTen = datastoreWrapper.leaderboardQuery()
		for result in topTen:
			logging.error(str(result.member_id) + " got high score: " + str(result.high_score))

class GameHandler(webapp.RequestHandler):
	def get(self):
		if self.request.headers.get('Cookie') == None:
			return self.redirect('/')
			
		#Get user info and connections
		
		cookie = self.request.headers.get('Cookie').split(';')
		
		for morsel in cookie:
			name,value = morsel.split('=')
			self.response.out.write("name: " + str(name) + " value: " + value + "<br />")

class IndexHandler(webapp.RequestHandler):
  def get(self):
    template_values = {      }

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))
 

class ReadyHandler(webapp.RequestHandler):
  def get(self):
    template_values = {      }

    path = os.path.join(os.path.dirname(__file__), 'ready.html')
    self.response.out.write(template.render(path, template_values))

class QuestionHandler(webapp.RequestHandler):
	def get(self):

		#score = self.request.get("score")
		cookie = self.request.headers.get('Cookie').split(';')
		for morsel in cookie:
			name,value = morsel.split('=')
			if name == 'memberId':
				memberId = value
				
		'''	if not score:
			score = 0
		#Gets and updates score in database
		totalScore = datastoreWrapper.updateScore(memberId,score)'''


		random.seed()
		n = random.randint(0, len(catagories)-1)
		#logging.error("random n = " + str(n))
		
		category = catagories[n]
				
		#peeps is list of 4 tuples, first one is answer to question
		#logging.error("memberId: " + str(memberId))
		logging.error("category: " + str(category))
		peeps = Question.choosePeople(category, memberId)
						
		ran = random.randint(0,3)
		temp = peeps[0]
		peeps[0] = peeps[ran]
		peeps[ran] = temp
		
		text = Question.getQuestionText(category, peeps[ran][0])
		j_son = json.dumps([{'questionText': text}, {'urls': [peeps[0][1], peeps[1][1],
				peeps[2][1], peeps[3][1]]}, {'answerId': ran}, {'category': category}])
		
		"""if category == 'publication' or category == 'patent':
			ran = 0
			text = Question.getQuestionText(category, peeps[ran])
			j_son = json.dumps([{'questionText': text}, {'urls': [peeps[0], peeps[1],
				peeps[2], peeps[3]]}, {'answerId': ran}, {'category': category}])
		else:
			text = Question.getQuestionText(category, peeps[ran][0])
			j_son = json.dumps([{'questionText': text}, {'urls': [peeps[0][1], peeps[1][1],
				peeps[2][1], peeps[3][1]]}, {'answerId': ran}, {'category': category}])"""
			
		#j_son = json.dumps([{'questionText': text}, {'urls': (answer.list[0].pic_url, answer.list[1].pic_url,
		#	answer.list[2].pic_url, answer.list[3].pic_url)}, {'answerId': answer.n}, {'catagory': category}])
		#logging.error("peeps: " + str(peeps))
		
		logging.error("json about to be returned: " + str(json))
		
		self.response.out.write(j_son)


def main():
	application = webapp.WSGIApplication([('/test', MainHandler),
	                                      ('/home', IndexHandler),
                                        ('/connections', LoginHandler),
																				('/verify', LoginHandler),
																				('/landing', LoginHandler),
																				('/ready', ReadyHandler),
      																	('/', LoginHandler),
      																  ('/leaders', LeaderboardHandler),
																				('/home', GameHandler),
																				('/getQuestion', QuestionHandler)],
                                         debug=True)
	util.run_wsgi_app(application)


if __name__ == '__main__':
	main()
